/** 全局中间件 */

const express = require("express");
const fs = require("fs");
const path = require("path");
const app = express();

/** 引入 body-parser 后  会新增 req.body 属性*/
const bodyParser = require('body-parser')
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// 全局注册
app.use(urlencodedParser)
app.use(jsonParser)



/** 全局中间件 */
function logMiddleware(req, res, next) {
  const { url, ip } = req;
  fs.appendFileSync(path.resolve(__dirname, "./log.txt"), `${url} ${ip} \r\n`);
  next();
}
/** 使用全局中间件 */
app.use(logMiddleware);

/** 路由中间件 */
const checkMiddleware = (req, res, next) => {
  if (req.query.admin == "admin") {
    next();
  } else {
    res.send("认证失败");
  }
};

app.get("/", (req, res) => {
  console.log(req.body);
  res.send("首页");
});

app.get("/home", (req, res) => {
  res.send("home");
});

app.get("/index", checkMiddleware, (req, res) => {
  res.send("index");
});

app.listen(3001, () => {
  console.log(" 3001 server start");
});
